package flc.ast.activity;

import android.Manifest;
import android.graphics.Bitmap;
import android.os.Handler;
import android.view.View;
import android.widget.SeekBar;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BasePopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.otaliastudios.cameraview.BitmapCallback;
import com.otaliastudios.cameraview.CameraException;
import com.otaliastudios.cameraview.CameraListener;
import com.otaliastudios.cameraview.CameraOptions;
import com.otaliastudios.cameraview.PictureResult;
import com.otaliastudios.cameraview.VideoResult;
import com.otaliastudios.cameraview.controls.Audio;
import com.otaliastudios.cameraview.controls.Facing;
import com.otaliastudios.cameraview.controls.Flash;
import com.otaliastudios.cameraview.controls.Mode;
import com.otaliastudios.cameraview.filter.Filters;
import com.otaliastudios.cameraview.size.SizeSelector;
import com.otaliastudios.cameraview.size.SizeSelectors;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.CameraFilterAdapter;
import flc.ast.bean.MyCameraFilterBean;
import flc.ast.bean.MyScaleBean;
import flc.ast.databinding.ActivityCameraBinding;
import flc.ast.dialog.ScaleDialog;
import stark.common.basic.event.usersys.IUserSysEvent;
import stark.common.basic.event.usersys.UserSysEventProxy;
import stark.common.basic.utils.DensityUtil;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.ProgressConvertUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.WorkPathUtil;

public class CameraActivity extends BaseAc<ActivityCameraBinding> {

    //相机设置
    private boolean isFlash = false;//判断是否打开闪光灯
    private int shotTime = 0;//拍摄延迟
    private float myBrightness = 1;//亮度
    private CameraOptions mCameraOptions;
    private int number;//拍照倒计时
    private Handler mHandler;
    private int mRecordTime;//拍摄视频的时间
    private boolean isShoot = false;
    private boolean isStart = false;
    //滤镜
    private CameraFilterAdapter filterAdapter;
    private int oldFilterPos = 0;
    private BasePopupView scalePopup;
    private ScaleDialog scaleDialog;

    @Override
    protected int onCreate() {
        return R.layout.activity_camera;
    }

    @Override
    protected void initView() {
        mDataBinding.ivCameraBack.setOnClickListener(v -> onBackPressed());

        mDataBinding.ivCameraReversal.setOnClickListener(this);
        mDataBinding.ivCameraScale.setOnClickListener(this);
        mDataBinding.tvCameraPicture.setOnClickListener(this);
        mDataBinding.tvCameraVideo.setOnClickListener(this);
        mDataBinding.ivCameraFlash.setOnClickListener(this);
        mDataBinding.tvCameraFilter.setOnClickListener(this);
        mDataBinding.tvCameraBrightness.setOnClickListener(this);
        mDataBinding.ivCameraStart.setOnClickListener(this);

        mHandler = new Handler();
        mRecordTime = 0;

        mDataBinding.sbBrightness.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (mCameraOptions != null) {
                    float exposureMinValue = mCameraOptions.getExposureCorrectionMinValue();
                    float exposureMaxValue = mCameraOptions.getExposureCorrectionMaxValue();
                    float value = ProgressConvertUtil.progress2value(progress, exposureMinValue, exposureMaxValue,
                            seekBar.getMax());
                    mDataBinding.cameraView.setExposureCorrection(value);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });
    }

    @Override
    protected void onClickCallback(View v) {
        int id = v.getId();
        if (id == R.id.ivCameraReversal) {//镜头反转
            reversalLens();
        } else if (id == R.id.ivCameraFlash) {//闪光灯
            openFlash();
        } else if (id == R.id.ivCameraScale) {//比例
            showScaleDialog();
        } else if (id == R.id.ivCameraStart) {//开始拍摄
            if (isStart) return;
            startShot();
        } else if (id == R.id.tvCameraFilter) {//滤镜
            mDataBinding.llBottomBrightness.setVisibility(View.GONE);
            mDataBinding.llBottomFilter.setVisibility(View.VISIBLE);
        } else if (id == R.id.tvCameraBrightness) {//亮度
            mDataBinding.llBottomFilter.setVisibility(View.GONE);
            mDataBinding.llBottomBrightness.setVisibility(View.VISIBLE);
        } else if (id == R.id.tvCameraPicture) {//拍摄图片模式
            isShoot = false;
            mDataBinding.tvVideoNum.setVisibility(View.GONE);
            mDataBinding.tvCameraPicture.setVisibility(View.INVISIBLE);
            mDataBinding.tvCameraVideo.setVisibility(View.VISIBLE);
            mDataBinding.tvCameraMode.setText(R.string.shoot_picture);
            mDataBinding.cameraView.setMode(Mode.PICTURE);
        } else if (id == R.id.tvCameraVideo) {//拍摄视频模式
            getRecordPermission();
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        //设置滤镜
        filterAdapter.getItem(oldFilterPos).setSelect(false);
        oldFilterPos = position;
        filterAdapter.getItem(position).setSelect(true);
        filterAdapter.notifyDataSetChanged();
        mDataBinding.cameraView.setFilter(filterAdapter.getItem(position).getFilter());
    }

    @Override
    protected void initData() {
        getPermission();
        //滤镜数据
        List<MyCameraFilterBean> mFilterList = new ArrayList<>();//滤镜集合
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text1), "#00000000", Filters.values()[0].newInstance(), true));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text2), "#323333", Filters.values()[1].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text3), "#C376F3", Filters.values()[2].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text4), "#6F7171", Filters.values()[3].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text5), "#505151", Filters.values()[4].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text6), "#999999", Filters.values()[5].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text7), "#513232", Filters.values()[6].newInstance(), false));
        mFilterList.add(new MyCameraFilterBean(getString(R.string.camera_filter_text8), "#787A7A", Filters.values()[7].newInstance(), false));
        mDataBinding.rvFilterList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        filterAdapter = new CameraFilterAdapter();
        mDataBinding.rvFilterList.setAdapter(filterAdapter);
        filterAdapter.setOnItemClickListener(this);
        filterAdapter.setList(mFilterList);
    }

    private void getPermission() {
        StkPermissionHelper.permission(Manifest.permission.CAMERA).reqPermissionDesc(getString(R.string.get_camera_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                //初始化相机
                initCameraView();
            }
        }).request();
    }

    private void getRecordPermission() {
        StkPermissionHelper.permission(Manifest.permission.RECORD_AUDIO).reqPermissionDesc(getString(R.string.get_record_permission)).callback(new StkPermissionHelper.ACallback() {
            @Override
            public void onGranted() {
                isShoot = true;
                mDataBinding.tvVideoNum.setVisibility(View.VISIBLE);
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.ivCameraStart.setImageResource(R.drawable.apstb);
                mDataBinding.tvCameraPicture.setVisibility(View.VISIBLE);
                mDataBinding.tvCameraVideo.setVisibility(View.INVISIBLE);
                mDataBinding.tvCameraMode.setText(R.string.shoot_video);
                mDataBinding.cameraView.setMode(Mode.VIDEO);
                mDataBinding.cameraView.setAudio(Audio.ON);
            }
        }).request();
    }

    //初始化相机
    private void initCameraView() {
        mDataBinding.cameraView.setMode(Mode.PICTURE);
        mDataBinding.cameraView.setAudio(Audio.OFF);
        mDataBinding.cameraView.setLifecycleOwner(this);
        int width = DensityUtil.getWith(mContext);
        int height = DensityUtil.getHeight(mContext);
        SizeSelector maxAreaSelector = SizeSelectors.maxArea(width * height);
        SizeSelector equalWidthSelector = SizeSelectors.withFilter(size -> size.getWidth() == width);
        mDataBinding.cameraView.setPictureSize(SizeSelectors.and(maxAreaSelector, equalWidthSelector));
        mDataBinding.cameraView.addCameraListener(new CameraListener() {
            @Override
            public void onCameraOpened(@NonNull CameraOptions options) {
                mCameraOptions = options;
            }

            @Override
            public void onCameraClosed() {
            }

            @Override
            public void onCameraError(@NonNull CameraException exception) {
            }

            @Override
            public void onPictureTaken(@NonNull PictureResult result) {
                //获取图片 去到预览界面
                int picWidth = result.getSize().getWidth();
                int picHeight = result.getSize().getHeight();
                int screenWidth = DensityUtil.getWith(mContext);
                int screenHeight = DensityUtil.getHeight(mContext);
                if (picWidth * picHeight > screenWidth * screenHeight) {
                    picWidth = screenWidth;
                    picHeight = screenHeight;
                }
                result.toBitmap(picWidth, picHeight, new BitmapCallback() {
                    @Override
                    public void onBitmapReady(@Nullable Bitmap bitmap) {
                        ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
                        ToastUtils.showShort(getString(R.string.save_to_local));
                    }
                });
            }

            @Override
            public void onVideoRecordingStart() {
                //开始拍摄视频
                startRecordTime();
            }

            @Override
            public void onVideoRecordingEnd() {
                //视频拍摄结束
                mDataBinding.tvVideoNum.setText("00:00");
                mDataBinding.ivCameraStart.setImageResource(R.drawable.apstb);
                stopRecordTime();
            }

            @Override
            public void onVideoTaken(@NonNull VideoResult result) {
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, result.getFile().getPath());
                ToastUtils.showShort(getString(R.string.save_to_local));
            }
        });
    }

    //反转镜头
    private void reversalLens() {
        Facing curFacing = mDataBinding.cameraView.getFacing();
        if (curFacing == Facing.BACK) {
            mDataBinding.cameraView.setFacing(Facing.FRONT);
        } else {
            mDataBinding.cameraView.setFacing(Facing.BACK);
        }
    }

    //打开闪光灯
    private void openFlash() {
        if (isFlash) {
            isFlash = false;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdg);
            shotTipText(getString(R.string.flash_close));
            mDataBinding.cameraView.setFlash(Flash.OFF);
        } else {
            isFlash = true;
            mDataBinding.ivCameraFlash.setImageResource(R.drawable.asgdk);
            shotTipText(getString(R.string.flash_open));
            mDataBinding.cameraView.setFlash(Flash.TORCH);
        }
    }

    //显示提示文字
    private void shotTipText(String text) {
        mDataBinding.tvCameraTipText.setText(text);
        mDataBinding.tvCameraTipText.setVisibility(View.VISIBLE);
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mDataBinding.tvCameraTipText.setVisibility(View.GONE);
            }
        }, 500);
    }

    //开始拍摄
    private void startShot() {
        if (!isShoot) {//照片拍摄
            if (mDataBinding.cameraView.isTakingPicture()) return;
            mDataBinding.cameraView.takePictureSnapshot();
        } else {//视频拍摄
            if (mDataBinding.cameraView.isTakingVideo()) {
                mDataBinding.cameraView.stopVideo();
            } else {
                String filePath = WorkPathUtil.generateVideoFilePath(null);
                if (filePath != null) {
                    mDataBinding.cameraView.takeVideoSnapshot(new File(filePath));
                }
            }
        }
    }

    private void showScaleDialog() {
        if (scaleDialog == null) scaleDialog = new ScaleDialog(mContext);
        scalePopup = new XPopup.Builder(mContext).popupPosition(PopupPosition.Right) //手动指定弹窗的位置
                .offsetX(-120)//x轴偏移
                .isDestroyOnDismiss(false) //对于只使用一次的弹窗，推荐设置这个
                .atView(mDataBinding.ivCameraScale).hasShadowBg(false) // 去掉半透明背景
                .asCustom(scaleDialog);
        scaleDialog.setListener(new ScaleDialog.Ilistener() {

            @Override
            public void click(MyScaleBean scaleBean) {
                ConstraintLayout.LayoutParams params = (ConstraintLayout.LayoutParams) mDataBinding.cameraView.getLayoutParams();
                params.dimensionRatio = scaleBean.getScale(); // 直接赋值比例字符串
                mDataBinding.cameraView.setLayoutParams(params);
                mDataBinding.ivCameraScale.setImageResource(scaleBean.getImg());
            }
        });
        scalePopup.show();
    }

    //开始拍摄视频
    private void startRecordTime() {
        mRecordTime = 0;
        mDataBinding.ivCameraStart.setImageResource(R.drawable.atzlz);
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
        mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
    }

    //结束拍摄视频
    private void stopRecordTime() {
        mHandler.removeCallbacks(mUpdateRecordTimeTask);
    }

    private final Runnable mUpdateRecordTimeTask = new Runnable() {
        @Override
        public void run() {
            mRecordTime++;
            mDataBinding.tvVideoNum.setText(TimeUtils.millis2String(mRecordTime * 1000L, "mm:ss"));
            mHandler.postDelayed(mUpdateRecordTimeTask, 1000);
        }
    };

}